package com.projectsexception.festivales;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.projectsexception.festivales.setup.FeedInfo;
import com.projectsexception.festivales.setup.MapInfo;
import com.projectsexception.festivales.setup.ProjectResources;
import com.projectsexception.festivales.setup.ShowInfo;
import com.projectsexception.festivales.setup.xml.XMLContentReader;

public class SetupActivity extends Activity {
    
    protected ProgressDialog mProgressDialog;
    private static SetupTask task;
    
    private class SetupTask extends AsyncTask<Void, Integer, Boolean> {
        
        private SetupActivity activity;
        
        public void setActivity(SetupActivity activity) {
            this.activity = activity;
        }
        
        @Override
        protected void onPreExecute() {
            activity.showDialog(0);
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            XMLContentReader provider = new XMLContentReader();
            ProjectResources data = ProjectResources.getInstance(activity);
            List<FeedInfo> feeds = provider.loadFeeds();
            publishProgress(20);
            data.insertFeeds(feeds);
            publishProgress(40);
            List<MapInfo> maps = provider.loadMaps();
            data.insertMaps(maps);
            publishProgress(60);
            List<ShowInfo> shows = provider.loadShows();
            publishProgress(80);
            data.insertShows(shows);
            publishProgress(100);

            return true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            activity.mProgressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            activity.tryDismissDialog(0);
            if (result) {
                activity.successTask();
            } else {
                activity.errorTask();                
            }
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setup);
        if (task != null && task.getStatus() == Status.RUNNING && !task.isCancelled()) {
            // La tarea se está ejecutando, le decimos que estamos aquí
            task.setActivity(this);
        } else {
            // No estamos conectados ni nada, empezamos
            setContentView(R.layout.setup);
            Button button = (Button) findViewById(R.id.start_button);
            button.setOnClickListener(new OnClickListener() {            
                @Override
                public void onClick(View arg0) {
                    startTask();
                }
            });
            
            button = (Button) findViewById(R.id.about_button);
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    showAbout();
                }
            });
            button = (Button) findViewById(R.id.exit_button);
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    finish();
                }
            });
        }
    } 

    protected void successTask() {
        startActivity(new Intent(this, MainActivity.class));
    }

    protected void errorTask() {
        Toast.makeText(this, "ERROR!", Toast.LENGTH_SHORT).show();
    }

    protected void startTask() {
        task = new SetupTask();
        task.setActivity(this);
        task.execute(new Void[0]);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("Conectando");
        mProgressDialog.setMessage("Extrayendo los datos del servidor");
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {            
            @Override
            public void onCancel(DialogInterface dialog) {
                if (task!=null && task.getStatus()==Status.RUNNING && !task.isCancelled()) {
                    task.cancel(true);
                }
            }
        });
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        return mProgressDialog;
    } 
    
    protected void tryDismissDialog(int id) {
        try {
            dismissDialog(id);      
        } catch (Exception e) {
            // No hay problema
        }
    }
    
    protected void showAbout() {
        Context context = getApplicationContext();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setIcon(R.drawable.icon);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        View about = inflater.inflate(R.layout.about, null);
        builder.setView(about);
        builder.setPositiveButton("OK", null);
        builder.create();
        builder.show();
    }

}
